16. Face Detection with OpenCV
Haar Cascades
OpenCV comes with a few Haar Cascade detectors already trained. If you want to train your own classifier for any object like a banana, car, etc. you can use OpenCV to create one. Its full details are given here.
For now, we'll just look at using a classifier to detect faces. First we need to load the required XML classifiers. Then load our input image (or video) in grayscale mode since face detection relies on patterns of intensity in an image.
import numpy as np
import cv2
# Load in the face detector XML file
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
# Read in an image
image = cv2.imread('face1.jpg')
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
#Convert to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Detect the faces in the image
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
This code will detect faces, and we'll see how we can use this to further analyze an image later on!